//
//  B_AddressSelectedVC.m
//  DreamOf
//
//  Created by 薛小刚 on 2018/9/6.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_AddressSelectedVC.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "B_AddressSearchView.h"
#import "B_TipsTableViewCell.h"
#import "B_AroundTableViewCell.h"
#import "B_MineHeaderMoreView.h"

@interface B_AddressSelectedVC ()<UIGestureRecognizerDelegate, MAMapViewDelegate, AMapSearchDelegate, AMapLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UIView *B_mapView;
@property (weak, nonatomic) IBOutlet UILabel *B_nowAddressLabel;
@property (weak, nonatomic) IBOutlet UIView *B_mainTableView;


@property (nonatomic, strong) BaseTableView * mainView;             // 大头针
@property (nonatomic, strong) MAMapView * mapView;                  // 地图
@property (nonatomic, strong) CLLocation * currentLocation;         // 经纬度
@property (nonatomic, strong) MAPointAnnotation * pointAnnotation;  // 定位
@property (nonatomic, strong) AMapSearchAPI * search;               // 搜索
@property (nonatomic, strong) B_AddressSearchView * searchView;     // 搜索的view
@property (nonatomic, strong) AMapInputTipsSearchRequest * tips;    // 提示语
@property (nonatomic, strong) AMapPOIKeywordsSearchRequest * searchRequest; // 搜索
@property (nonatomic, strong) AMapReGeocodeSearchRequest * reGeocode;   // 地里位置翻遍吗

@property (nonatomic, strong) BaseTableView * tipsTableview;       // 提示语的表格
@property (nonatomic, strong) BaseTableView * aroundTableview;      // 周围的表格

@property (nonatomic, strong) NSMutableArray * tipsArray;           // 提示语的数组
@property (nonatomic, strong) NSMutableArray * aroundArray;         // 周报数据的数组

@end

@implementation B_AddressSelectedVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"地址选择"];
    self.view.frame = [UIScreen mainScreen].bounds;
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    ///初始化地图
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 300)];
    [self.B_mapView addSubview:_mapView];
    [_mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.B_mapView);
    }];
    _pointAnnotation = [[MAPointAnnotation alloc] init];
    _mapView.delegate = self;
    [_mapView setZoomLevel:17.5 animated:YES];
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_mapView addGestureRecognizer:tap];
    tap.delegate = self;
    ///把地图添加至view
    
    [self.B_mapView addSubview:self.searchView];
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mapView.mas_top).offset(5);
        make.left.equalTo(self.mapView.mas_left).offset(16);
        make.right.equalTo(self.mapView.mas_right).offset(-16);
        make.height.equalTo(@(38));
    }];
    // 定位
    [[B_GaoDeManager shareGaoDeManager] startLocation:^(CLLocation *location) {
        self.currentLocation = location;
        [self initSearchs];
        self.reGeocode.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
        [self.search AMapReGoecodeSearch:self.reGeocode];
    }];
    
    [self.B_mainTableView addSubview:self.aroundTableview];
    [self.aroundTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.B_mainTableView);
    }];
}

- (B_AddressSearchView *)searchView {
    if (!_searchView) {
        WeakSelf(weSelf, self);
        _searchView = [[B_AddressSearchView alloc] init];
        _searchView.searchAction = ^(NSString *string, BOOL isSearch) {
            //TODO:搜索
            if (isSearch) {     /// 搜索
                weSelf.searchRequest.keywords = string;
                [weSelf.search AMapPOIKeywordsSearch:weSelf.searchRequest];
                if (weSelf.tipsTableview.superview) {
                    [weSelf.tipsTableview removeFromSuperview];
                }
            } else {            /// 提示语
                weSelf.tips.keywords = string;
                [weSelf.search AMapInputTipsSearch:weSelf.tips];
            }
        };
    }
    return _searchView;
}

- (AMapSearchAPI *)search {
    if (!_search) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return _search;
}

- (AMapPOIKeywordsSearchRequest *)searchRequest {
    if (!_searchRequest) {
        _searchRequest = [[AMapPOIKeywordsSearchRequest alloc] init];
        _searchRequest.requireExtension    = YES;
        _searchRequest.cityLimit           = YES;
        _searchRequest.requireSubPOIs      = YES;
    }
    return _searchRequest;
}

- (AMapInputTipsSearchRequest *)tips {
    if (!_tips) {
        _tips = [[AMapInputTipsSearchRequest alloc] init];
        _tips.cityLimit = YES;
    }
    return _tips;
}

- (AMapReGeocodeSearchRequest *)reGeocode {
    if (!_reGeocode) {
        _reGeocode = [[AMapReGeocodeSearchRequest alloc] init];
        _reGeocode.requireExtension            = YES;
    }
    return _reGeocode;
}


#pragma mark - 允许多手势响应
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (void) tapAction:(UITapGestureRecognizer *) tap {
    [self.searchView endEditing:YES];
    [_mapView removeAnnotation:_pointAnnotation];
    //坐标转换
    CGPoint touchPoint = [tap locationInView:_mapView];
    CLLocationCoordinate2D touchMapCoordinate = [_mapView convertPoint:touchPoint toCoordinateFromView:_mapView];
    _pointAnnotation.coordinate = touchMapCoordinate;
    [_mapView addAnnotation:_pointAnnotation];
    
    [self setLocationWithLatitude:touchMapCoordinate.latitude AndLongitude:touchMapCoordinate.longitude];
    if (self.tipsTableview.superview) {
        [self.tipsTableview removeFromSuperview];
    }
}



- (void)setLocationWithLatitude:(CLLocationDegrees)latitude AndLongitude:(CLLocationDegrees)longitude{
    
//    NSString *latitudeStr = [NSString stringWithFormat:@"%f",latitude];
//    NSString *longitudeStr = [NSString stringWithFormat:@"%f",longitude];
    self.currentLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];;
    [self initSearchs];
    //反编码 经纬度---->位置信息
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error) {
            NSLog(@"反编码失败:%@",error);
        }else{
            //NSLog(@"反编码成功:%@",placemarks);
            CLPlacemark *placemark=[placemarks lastObject];
            //NSLog(@"%@",placemark.addressDictionary[@"FormattedAddressLines"]);
            NSDictionary *addressDic=placemark.addressDictionary;
            NSString *state=[addressDic objectForKey:@"State"];
            NSString *city=[addressDic objectForKey:@"City"];
            NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
            NSString *street=[addressDic objectForKey:@"Street"];
            NSLog(@"%@,%@,%@,%@",state,city,subLocality,street);
            NSString *strLocation;
            if (street.length == 0 || street == NULL || [street isEqualToString:@"(null)"]) {
                strLocation= [NSString stringWithFormat:@"%@%@%@",state,city,subLocality];
            } else {
                strLocation= [NSString stringWithFormat:@"%@%@%@%@",state,city,subLocality,street];
            }
            self.B_nowAddressLabel.text = strLocation;
        }
    }];
}

- (void) initSearchs {
    if (_currentLocation == nil || self.search == nil) {
        return;
    }
    AMapPOIAroundSearchRequest * request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
    request.sortrule = 0;
    request.requireExtension = YES;
    [_search AMapPOIAroundSearch:request];
    
}


/**
 搜索回调

 @param request 请求
 @param response 返回
 */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    if (response.pois.count == 0) {
        return;
    }
    self.aroundArray = [NSMutableArray array];
    [self.aroundArray removeAllObjects];
    for (AMapPOI * poi in response.pois) {
        [self.aroundArray addObject:poi];
        NSLog(@"name is %@ address is %@", poi.name, poi.address);
    }
    [self.aroundTableview.tableView reloadData];
}

/* 输入提示回调. */
- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
{
    //解析response获取提示词，具体解析见 Demo
    HXLog(@"response is %@", response.tips);
    if (!self.tipsTableview.superview) {
        [self.B_mapView addSubview:self.tipsTableview];
        [self.tipsTableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.searchView.mas_bottom).offset(2);
            make.left.equalTo(self.searchView.mas_left);
            make.right.equalTo(self.searchView.mas_right);
            make.height.equalTo(@(200));
        }];
    }
    self.tipsArray = [NSMutableArray array];
    [self.tipsArray removeAllObjects];
    for (AMapTip * tips in response.tips) {
        [self.tipsArray addObject:tips];
        HXLog(@"tips name is %@", tips.name);
    }
    [self.tipsTableview.tableView reloadData];
    
}
/* 逆地理编码回调. */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil)
    {
        //解析response获取地址描述，具体解析见 Demo
        NSLog(@"response %@", response.regeocode.formattedAddress);
        /// 展示当前位置信息
        self.searchRequest.city = response.regeocode.addressComponent.city;
        self.tips.city = response.regeocode.addressComponent.city;
        self.B_nowAddressLabel.text = response.regeocode.formattedAddress;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (BaseTableView *)tipsTableview {
    if (!_tipsTableview) {
        WeakSelf(weSelf, self);
        _tipsTableview = [[BaseTableView alloc] init];
        [_tipsTableview setTableViewFrameWithTop:0 left:0 right:0 bottom:0];
        [_tipsTableview.tableView registerNib:[UINib nibWithNibName:@"B_TipsTableViewCell" bundle:nil] forCellReuseIdentifier:@"B_TipsTableViewCell"];
        _tipsTableview.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            return weSelf.tipsArray.count;
        };
        _tipsTableview.heightForRowBlock = ^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return 45;
        };
        _tipsTableview.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            AMapTip * tips = weSelf.tipsArray[indexPath.row];
            B_TipsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"B_TipsTableViewCell" forIndexPath:indexPath];
            cell.B_tipsLabel.text = tips.name;
            
            return cell;
        };
        _tipsTableview.didSelectRow = ^(UITableView *tableView, NSIndexPath *indexPath) {
            AMapTip * tips = weSelf.tipsArray[indexPath.row];
            weSelf.searchRequest.keywords = tips.name;
            [weSelf.search AMapPOIKeywordsSearch:weSelf.searchRequest];
            if (weSelf.tipsTableview.superview) {
                [weSelf.tipsTableview removeFromSuperview];
            }
        };
    }
    return _tipsTableview;
}


- (BaseTableView *)aroundTableview {
    if (!_aroundTableview) {
        WeakSelf(weSelf, self);
        _aroundTableview = [[BaseTableView alloc] init];
        [_aroundTableview setTableViewFrameWithTop:0 left:0 right:0 bottom:0];
        [_aroundTableview.tableView registerNib:[UINib nibWithNibName:@"B_AroundTableViewCell" bundle:nil] forCellReuseIdentifier:@"B_AroundTableViewCell"];
        _aroundTableview.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            return weSelf.aroundArray.count;
        };
        _aroundTableview.heightForRowBlock = ^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return 66;
        };
        _aroundTableview.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            AMapPOI * poi = weSelf.aroundArray[indexPath.row];
            B_AroundTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"B_AroundTableViewCell" forIndexPath:indexPath];
            cell.B_titleLabel.text = poi.name;
            cell.B_contentLabel.text = poi.address;
            return cell;
        };
        _aroundTableview.didSelectRow = ^(UITableView *tableView, NSIndexPath *indexPath) {
            AMapPOI * poi = weSelf.aroundArray[indexPath.row];
            if (weSelf.addressSelected) {
               weSelf.addressSelected(poi);
            }
            [weSelf.navigationController popViewControllerAnimated:YES];
        };
        _aroundTableview.heightForHeaderBlock = ^CGFloat(UITableView *tableView, NSInteger section) {
            return 50;
        };
        _aroundTableview.viewForHeaderBlock = ^UIView *(UITableView *tableView, NSInteger section) {
            B_MineHeaderMoreView * header = [B_MineHeaderMoreView initB_MineHeaderMoreView];
            header.moreButton.hidden = YES;
//            header.B_leftImageView.image = [UIImage getImageWithColor:[UIColor color_yellow] alp:1];
            header.B_titleLabel.text = @"周边地点";
            header.B_titleLabel.textColor = [UIColor color_text_light_gray];
            header.backgroundColor = [UIColor color_content_background_color];
            return header;
        };
    }
    return _aroundTableview;
}



@end
